<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>百度翻译</title>
</head>

<body>

  <p>
    <textarea id="textarea0" cols="30" rows="10" placeholder="请输入中文">你好</textarea>
  </p>
  <p>
    <textarea id="textarea1" cols="30" rows="10" placeholder="翻译结果"></textarea>
  </p>
  <p>
    <button onclick="translate2Eng()">翻译为英文</button>
  </p>


  <script src="https://cdn.sheetjs.com/xlsx-0.19.1/package/dist/xlsx.full.min.js"></script>
  <script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script>
  <script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js"></script>
  <script>


    const BAIDI_apiUrl = 'http://api.fanyi.baidu.com/api/trans/vip/translate';
    const BAIDI_appid = "20241218002231212" // APP ID
    const BAIDI_secret = "JpkRUxu42G5coenLP9se" // 密钥

    // 翻译为英文
    function translate2Eng (val, fn) {
      const inputVal0 = $textArea = $('#textarea0')
      const inputVal1 = $textArea = $('#textarea1')
      const q = inputVal0.val() || '无值'
      // debugger
      const salt = Math.random();
      const sign = md5(BAIDI_appid + q + salt + BAIDI_secret);
      const data = {
        q,
        from: 'zh',
        to: 'en',
        salt,
        appid: BAIDI_appid,
        sign,
      };

      // debugger
      $.ajax({
        url: BAIDI_apiUrl,
        type: 'get',
        dataType: 'jsonp',
        data,
        success: function (res) {
          // console.log(data);
          // debugger
          inputVal1.val(res.trans_result[0].dst)
          fn && fn(res)
        },
        error: function (err) {
          console.error(err);
          // debugger
        }
      });
    }

  </script>
</body>

</html>